using UnityEngine;
using System.Collections;

public class Conection : MonoBehaviour {
	
	
	public string remoteIP = "127.0.0.1";
    public int remotePort = 25000;
    public int listenPort = 25000;
    public bool useNAT = false;
    public string yourIP = "";
    public string yourPort = "";
	
	
	public Transform player;
	public Transform _camera;
	
	Object tempPlayer;
	Object tempCamera;
	
	public GameObject[] respawns;
	public GameObject[] players;
	
	public int id = 0;
	
	// Use this for initialization
	void Start () {
	
		respawns = GameObject.FindGameObjectsWithTag("Respawn");
		
	}
	
	// Update is called once per frame
	void Update () {
	
		players = GameObject.FindGameObjectsWithTag("Player");
		
		if (Network.peerType == NetworkPeerType.Disconnected)
		{
			for (int i = 0; i < players.Length; i++)
			{
				Destroy(players[i]);
			}
		}
	}
	
	void  OnConnectedToServer ()
    {
		CreateNewPlayer();
    }
	
	void OnServerInitialized() {
		
		CreateNewPlayer();
		
        Debug.Log("Server initialized and ready");
    }
	
	void OnGUI()
    {
        // Checking if you are connected to the server or not
        if (Network.peerType == NetworkPeerType.Disconnected)
        {
            // If not connected
            if (GUI.Button (new Rect(10,10,100,30),"Connect"))
            {
				Network.Connect(remoteIP, remotePort);
            }
            if (GUI.Button (new Rect(10,50,100,30),"Start Server"))
            {
				Network.InitializeServer(32, listenPort, useNAT);
            }

            // Fields to insert ip address and port 
            remoteIP = GUI.TextField(new Rect(120,10,100,20),remoteIP);
            remotePort = int.Parse(GUI.TextField(new Rect(230,10,40,20),remotePort.ToString()));

        }
        else//connected...
        {

            GUI.Label(new Rect(140,20,250,40),
                "IP Adress: " + Network.player.ipAddress + ":" + Network.player.port.ToString());

            if (GUI.Button (new Rect(10,10,100,50),"Disconnect"))
            {
                // Disconnect from the server
                Network.Disconnect(200);
            }
        }
    }
	
	void CreateNewPlayer()
    {
		
		if(respawns != null)
		{
			if (respawns.Length < id)
				id = id - respawns.Length;
			
			tempPlayer = Network.Instantiate(player, respawns[id].transform.position, transform.rotation, 0);
		}else
		{
			tempPlayer = Network.Instantiate(player, new Vector3(0, 5, 0), transform.rotation, 0);
		}
		
		tempCamera = Instantiate(_camera, Vector3.zero, _camera.transform.rotation);
		
		tempPlayer.name = "" + id;
		
		tempCamera.name = "" + id;
		
		//Player.ID = id;
		//RotatePlayer_Camera.ID = id;
		id++;
	}
	
	void OnPlayerDisconnected(NetworkPlayer player)
    {
        Network.RemoveRPCs(player, 0);
        Network.DestroyPlayerObjects(player);
		
    }
}
